import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Steps, List, Typography, Tag, Divider, Spin } from 'antd';
import { ShoppingOutlined } from '@ant-design/icons';
import { Order } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text } = Typography;

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    if (id) {
      const orders = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
      const found = orders.find(o => o.id === id);
      setOrder(found || null);
    }
    setLoading(false);
  }, [id]);

  const getStatusInfo = (status: Order['status']) => {
    const statusMap = {
      pending: { text: '待付款', color: 'orange' },
      paid: { text: '已付款', color: 'blue' },
      shipped: { text: '已发货', color: 'cyan' },
      delivered: { text: '已送达', color: 'green' },
      cancelled: { text: '已取消', color: 'red' }
    };
    return statusMap[status];
  };

  const getStepStatus = (status: Order['status']) => {
    const stepMap = {
      pending: 0,
      paid: 1,
      shipped: 2,
      delivered: 3,
      cancelled: 0
    };
    return stepMap[status];
  };

  if (loading) {
    return <div style={{ textAlign: 'center', padding: '50px 0' }}><Spin size="large" /></div>;
  }

  if (!order) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Text>订单不存在</Text>
        <br />
        <Button type="primary" onClick={() => navigate('/')}>返回首页</Button>
      </div>
    );
  }

  const statusInfo = getStatusInfo(order.status);

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Title level={2}>订单详情</Title>

      {/* 订单状态 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <div>
            <Text strong>订单状态：</Text>
            <Tag color={statusInfo.color} style={{ marginLeft: 8 }}>
              {statusInfo.text}
            </Tag>
          </div>
          <Text type="secondary">订单号：{order.id}</Text>
        </div>

        {order.status !== 'cancelled' && (
          <Steps
            current={getStepStatus(order.status)}
            items={[
              { title: '提交订单' },
              { title: '付款' },
              { title: '发货' },
              { title: '收货' }
            ]}
          />
        )}
      </Card>

      {/* 收货信息 */}
      <Card title="收货信息" style={{ marginBottom: 16 }}>
        <div style={{ marginBottom: 8 }}>
          <Text strong>收货人：</Text>
          <Text>{order.address.name}</Text>
        </div>
        <div style={{ marginBottom: 8 }}>
          <Text strong>联系电话：</Text>
          <Text>{order.address.phone}</Text>
        </div>
        <div>
          <Text strong>收货地址：</Text>
          <Text>
            {order.address.province} {order.address.city} {order.address.district} {order.address.detail}
          </Text>
        </div>
      </Card>

      {/* 商品信息 */}
      <Card title="商品信息" style={{ marginBottom: 16 }}>
        <List
          dataSource={order.items}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={
                  <img
                    src={item.product.image}
                    alt={item.product.name}
                    style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }}
                  />
                }
                title={item.product.name}
                description={
                  <div>
                    <Text>单价: ¥{item.price}</Text>
                    <br />
                    <Text>数量: {item.quantity}</Text>
                  </div>
                }
              />
              <div>
                <Text className="price-current">
                  ¥{(item.price * item.quantity).toFixed(2)}
                </Text>
              </div>
            </List.Item>
          )}
        />
        
        <Divider />
        
        <div style={{ textAlign: 'right' }}>
          <Text style={{ fontSize: 16 }}>
            商品总价: <span className="price-current">¥{order.totalAmount.toFixed(2)}</span>
          </Text>
        </div>
      </Card>

      {/* 订单信息 */}
      <Card title="订单信息">
        <div style={{ marginBottom: 8 }}>
          <Text strong>创建时间：</Text>
          <Text>{new Date(order.createdAt).toLocaleString()}</Text>
        </div>
        <div style={{ marginBottom: 8 }}>
          <Text strong>更新时间：</Text>
          <Text>{new Date(order.updatedAt).toLocaleString()}</Text>
        </div>
        
        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <Button onClick={() => navigate(-1)} style={{ marginRight: 16 }}>
            返回
          </Button>
          <Button type="primary" icon={<ShoppingOutlined />} onClick={() => navigate('/')}>
            继续购物
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default OrderDetail;
